<template>
  <base-breadcrumb>
    <a-card>
      <div class="table-page-search-wrapper">
        <title-name
          v-if="isEdit == 0"
          title="新增设计资料"
        />
        <title-name
          v-if="isEdit == 1"
          title="编辑设计资料"
        />
        <a-form-model
          ref="form1"
          layout="horizontal"
          :model="form"
          :rules="rules"
        >
          <a-row :gutter="24">
            <a-col
              :md="16"
              :sm="16"
            >
              <!--              designTypeNames: ["a1类", "a2类", "a3类"]-->
              <a-form-model-item
                label="所属单位"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="projectId"
              >
                <org-tree-select
                  v-model="form.projectId"
                  is-auto-select-first
                  is-need-auth
                  is-special-tree
                  :is-query-projec-detail="false"
                  :extra-query="{
                    designTypeNames: ['a1类', 'a2类', 'a3类']
                  }"
                  check-strictly
                  @select="selectOrg"
                  @change="getPojectDetails(form.projectId)"
                />
              </a-form-model-item>
            </a-col>
            <!--            <a-col-->
            <!--              :md="8"-->
            <!--              :sm="8"-->
            <!--            >-->
            <!--              <a-form-model-item-->
            <!--                label="分公司"-->
            <!--                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
            <!--                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
            <!--                prop="branchId"-->
            <!--              >-->
            <!--                <SelectSubCompany-->
            <!--                  v-model="form.branchId"-->
            <!--                  placeholder="请选择"-->
            <!--                />-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <!--            <a-col-->
            <!--              :md="8"-->
            <!--              :sm="8"-->
            <!--            >-->
            <!--              <a-form-model-item-->
            <!--                label="项目名称"-->
            <!--                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
            <!--                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
            <!--                prop="projectId"-->
            <!--              >-->
            <!--                <SelectProject-->
            <!--                  v-model="form.projectId"-->
            <!--                  placeholder="请选择"-->
            <!--                  :form="form"-->
            <!--                  :is-clear="true"-->
            <!--                  :design-type-name="true"-->
            <!--                  key-value="branchId"-->
            <!--                  @change="getPojectDetails(form.projectId)"-->
            <!--                />-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目设计管理类别"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="form.projectType"
                  placeholder=""
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="设计资料名称"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="resultName"
              >
                <BaseInput
                  v-model="form.resultName"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="设计资料类型"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="resultTypeId"
              >
                <a-select
                  v-model="form.resultTypeId"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="(item, index) in resultTypes"
                    :key="index"
                    :value="item.id"
                  >
                    {{
                      item.name
                    }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="图纸版本号"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="versionNum"
              >
                <BaseInput
                  v-model="form.versionNum"
                  placeholder="输入图纸版本号"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="出图时间"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="drawTime"
              >
                <a-date-picker
                  v-model="form.drawTime"
                  style="width: 100%"
                  @change="onChangeTime"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="设计单位名称"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="designUnit"
              >
                <b-input
                  v-model="form.designUnit"
                  placeholder="请选择或输入"
                />
              </a-form-model-item>
            </a-col>
            <a-button
              type="primary"
              @click="changeData"
            >
              选择
            </a-button>
            （从设计资源库中选择）
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="创建人"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="form.creator"
                  placeholder=""
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="创建时间"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="currentDate"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="设计资料概述"
                :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
                :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }"
                prop="resultInfo"
              >
                <editor
                  v-model="form.resultInfo"
                  :is-clear="true"
                  @change="editorContent"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <title-name title="设计资料相关资料上传" />
        <!--<u-table :listUrl="listUrl" :uploadList="uploadList" :businessId="businessId"  :deleteUrl="deleteUrl" businessCode="PM16" @fileArrysData=fileArrysData></u-table>-->
        <a-upload
          :disabled="spinning"
          name="file"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          @change="handleChanges"
        >
          <a-button
            :loading="spinning"
            type="primary"
            icon="upload"
            style="margin-bottom: 20px"
          >
            上传
          </a-button>
        </a-upload>
        <a-button
          :disabled="selectedRowKeys.length === 0"
          icon="delete"
          style="margin-bottom: 20px; margin-left: 20px"
          @click="deleteExteriorFile()"
        >
          删除
        </a-button>
        <a-table
          bordered
          :columns="columnAssment"
          :loading="spinning"
          :data-source="dataAssement"
          :row-selection="rowSelections"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span><span
            slot="action"
            slot-scope="text, record"
          >
            <a
              :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId"
              target="_parent"
            >导出</a>
            <a-divider
              type="vertical"
            />
            <a
              href="javascript:"
              @click="$filePreview(record)"
            >预览</a>
          </span>
        </a-table>

        <a-modal
          v-model="visible"
          width="900px"
          :title="title"
        >
          <template slot="footer">
            <a-button
              key="back"
              @click="handleCancel"
            >
              取消
            </a-button>
            <a-button
              key="submit"
              type="primary"
              @click="handleOk"
            >
              确定选择
            </a-button>
          </template>

          <searchData
            :search-data="searchArr"
            @search="searchDatas"
          />

          <a-table
            bordered
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange, type: 'radio' }"
            :columns="columns"
            :data-source="tableData"
            row-key="id"
          >
            <span
              slot="serial"
              slot-scope="text, record, index"
            >{{ index + 1 }}</span>
          </a-table>
          <pagination
            v-model="pageNo"
            :total="totalSize"
            :page-size.sync="pageSize"
            @change="handlePageChange"
            @showSizeChange="showSizeChange"
          />
        </a-modal>
      </div>
    </a-card>

    <div class="page-btn-right-top">
      <a-button
        type="primary"
        @click="saveDraft"
      >
        保存草稿
      </a-button>
      <a-button
        class="ml12"
        :loading="loading"
        type="primary"
        @click="submit"
      >
        提交
      </a-button>
      <a-button
        class="ml12"
        type="primary"
        @click="goBack"
      >
        关闭
      </a-button>
    </div>
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import { getDesignResourcesList } from '@/api/design/parameter'
import { getLaborSubcontractors } from '@/api/subcontractors/labor'
import { getTypes, getLabelTypes } from '@/api/commons'
import {
  addDesignResult,
  getDesignDetails,
  editDesignResult,
  getTypeLabels,
  deleteDesignResultFile
} from '@/api/project/designResult'
import { getProjectBranchType } from '@/api/project/designChange'
import { uploadFile, deleteUploadFile } from '@/api'
import { getProject } from '@/api/themeChoose/themeChoose'
import editor from '@/components/Editor/editor'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/SelectProjects/SelectProject' // 项目


import ARow from 'ant-design-vue/es/grid/Row'

const columns = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '设计资源名称',
    dataIndex: 'name',
    width: '20%'
  },
  {
    title: '设计资源类型',
    dataIndex: 'resTypeName',
    width: '30%'
  },
  {
    title: '设计资源等级',
    dataIndex: 'resLevelName',
    width: '30%'
  }
]

const columnAssment = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    editor,
    SelectSubCompany,
    SelectProject
  },
  data() {
    return {
      resSearchQuery: {}, // 设计资源搜索参数
      columnAssment,
      placeholder: '请选择',
      fetching: false, // 加载状态
      loading: false,
      spinning: false,
      editorOption: {
        placeholder: '输入设计资料信息'
      },

      projectNames: [], // 项目
      dataAssement: [],

      TiLength: 0,
      uploadFile: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      fileIds: [],

      businessCode: 'PM16',

      selectedRowKeys: [],
      selectedRows: [],
      selectId: [],

      columns,
      pageNo: 1,
      pageSize: 20,

      selectMaxLength: 30,

      tableData: [],//总数据
      totalSize: 0,
      totalPage: 0,
      searchArr: [
        // 搜索框
        {
          name: '设计资源名称',
          value: 'designResourceName',
          type: 'input'
        },
        {
          name: '设计资源类型',
          value: 'resTypeId',
          type: 'select',
          data: []
        },
        {
          name: '设计资源等级',
          value: 'resLevelId',
          type: 'select',
          data: []
        }
      ],

      // 资料上传
      listUrl: '',
      deleteUrl: '/cscec-project-business/file/business/project-fileDelete',
      uploadList: '/cscec-project-business/file/business/fileUpload',
      businessId: '',

      data: [],
      resultTypes: [], //  设计资料类型
      visible: false,
      title: '选择设计资源',

      form: {
        creator: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        projectType: '',
        designUnit: ''
      },
      currentDate: '', // 当前日期

      selectedRowKey: [],
      selectedRow: [],
      selectRow: [],

      isEdit: '',
      id: '',

      companys: [],

      rules: {
        branchId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        resultName: [{ required: true, message: '请输入设计资料名称', trigger: 'blur' }],
        resultInfo: [{ required: true, message: '请输入设计资料概述', trigger: 'blur' }],
        designUnit: [{ required: true, message: '请选择或输入设计单位名称', trigger: 'change' }],
        resultTypeId: [{ required: true, message: '请选择设计资料类型', trigger: 'change' }],
        versionNum: [{ required: true, message: '请输入图纸版本编号', trigger: 'blur' }],
        drawTime: [{ required: true, message: '请选择出图时间', trigger: 'change' }]
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
    }
  },

 async created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id
    this.isEdit = this.$route.query.isEdit

    this.getDesignResourcesList()
    this.getTypes()
    if (this.isEdit == 1) {
      this.getDesignDetails()
    }
    this.getCurrentDate() // 获取当前日期
    this.getTypeLabels() // 获取当前日期
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('design_achievement')
  },
  computed: {
    rowSelections() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChanges
      }
    }
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKey,
    //     selectedRows: this.selectedRow,   // 当前行所有数据
    //     onChange: this.onSelectChange
    //   }
    // },
  },
  methods: {
    selectOrg(val) {
      if(val.length>1) {
        this.form.branchId = val[val.length - 2].orgId
        this.getPojectDetails(this.form.projectId)
      }
    },
    deleteExteriorFile() {
      let that = this
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            // 删除时，需要用commonId
            // deleteDesignResultFile({ businessId: that.id, fileList: that.fileFileds.split(',') }).then((res) => {
            //   if (res.code == 200 || res.data.code == 200) {
            //     that.$message.success('删除附件成功！')
            //
            //
            //
            //   }
            // })

            let data = that.dataAssement
            let selectDatas = that.fileFileds
            that.dataAssement = data.filter((item) => {
              return !selectDatas.includes(item.commonId)
            })

            that.form.fileList = that.dataAssement
            that.selectedRowKeys = []
            that.selectedRows = []
            that.$message.success('删除成功')
          },
          onCancel() {
          }
        })
      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            deleteUploadFile({ fileIds: that.fileFileds }).then((res) => {
              if (res.code == '0' || res.data.code == '0') {
                let data = that.dataAssement
                let selectDatas = that.fileFileds
                that.dataAssement = data.filter((item) => {
                  return !selectDatas.includes(item.commonId)
                })
                that.form.fileList = that.dataAssement
                that.selectedRowKeys = []
                that.selectedRows = []
                that.$message.success('删除成功')
              }
            })
          },
          onCancel() {
          }
        })
      }
    },

    onSelectChanges(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let fileFileds = []
      let fileIds = []
      selectedRows.forEach(function(obj, i) {
        fileFileds.push(obj.commonId) //
        fileIds.push(obj.fileId)
      })
      this.fileFileds = fileFileds.join(',')
      this.fileIds = fileIds // 有业务id 删除附件
    },
    // 上传

    beforeUpload(info) {
      this.uploadFile = info
      return false
    },

    handleChanges(info) {
      const data = new FormData()
      data.append('file', this.uploadFile)
      data.append('businessCode', this.businessCode)
      this.selectedRowKeys = []
      let arr = []
      this.spinning = true
      uploadFile(data)
        .then((res) => {
          this.spinning = false
          if (res.code === 200) {
            arr.push(res.data)
            if (this.dataAssement == null) {
              this.dataAssement = arr
            } else {
              this.dataAssement = this.dataAssement.concat(arr)
            }

            this.form.fileList = this.dataAssement
          }
        })
        .catch((res) => {
          this.spinning = false
        })
    },

    getTypes() {
      getLabelTypes({ type: 13 }).then((res) => {
        this.searchArr[2].data = this.getChangeDatatTypes(res.data)
      })

      getLabelTypes({ type: 14 }).then((res) => {
        this.searchArr[1].data = this.getChangeDatatTypes(res.data)
      })
    },
    getCurrentDate() {
      var d1 = new Date()
      var year = d1.getFullYear() //年
      var month = d1.getMonth() + 1 //月
      var day = d1.getDate() //日

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.currentDate = year + '-' + month + '-' + day
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.getDesignResourcesList()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.getDesignResourcesList()
    },

    getDesignResourcesList: function() {
      let searchData = Object.assign({ pageSize: this.pageSize, pageNo: this.pageNo }, this.resSearchQuery)
      getDesignResourcesList(searchData).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data
          this.totalSize = res.totalSize
          this.totalPage = res.totalPage
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectRow = selectedRows[0]
      this.selectedRowKey = selectedRowKeys
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    scrollMore(e) {
      const { target } = e
      var total = target.scrollTop + target.offsetHeight
      var scrollHeight = target.scrollHeight

      // this.pageNo是当前页 this.totalPage是总页数
      if (total >= scrollHeight - 1 && total < scrollHeight + 1 && this.pageNo <= this.totalPage) {
        this.pageNo = this.pageNo + 1
        this.getDesignResourcesList() // 调用api方法
      }
    },

    getDesignUnitId(val) {
      this.form.designUnit = val.substr(0, this.selectMaxLength)
      const target = this.tableData.find((item) => item.name)
      this.form.designUnitId = target.id
    },

    searchDatas(val) {
      this.resSearchQuery = val || {}
      this.pageNo = 1
      this.getDesignResourcesList(val)
    },

    getTypeLabels() {
      getTypeLabels({ type: 21 }).then((res) => {
        if (res.code == 200) {
          this.resultTypes = res.data
        }
      })
    },

    getPojectDetails(val) {
      let obj = {}
      let arr = []
      arr.push(val)
      obj.projectIds = arr
      obj.pageNo = 1
      obj.pageSize = 10
      getProjectBranchType(obj).then((res) => {
        this.form.projectType = res.data[0].designTypeName
      })
    },
    goBack() {
     this.$router.back()
    },
    saveDraft() {
      // 保存草稿
      this.form.statusCode = 0

      if (this.form.designUnit.length > 30) {
        this.$message.error('设计单位名称不能超过30个字符！')
        return
      }

      if (this.id) {
        this.form.id = this.id
        editDesignResult(this.form).then((res) => {
          if (res.data.code == 200) {
            this.$message.success('保存草稿成功')
            this.goBack()
          }
        })
      } else {
        addDesignResult(this.form).then((res) => {
          if (res.data.code == 200) {
            this.$message.success('保存草稿成功')
            this.goBack()
          }
        })
      }
    },
    submit() {
      this.setProcessConfig = null;
      this.$refs.form1.validate((err, values) => {
        if (err) {
          if (this.loading.isSubmit) return

          if (this.form.designUnit.length > 30) {
            this.$message.error('设计单位名称不能超过30个字符！')
            return
          }
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              return
            }
            if (this.id) {
              this.loading = true
              this.form.id = this.id
              this.form.statusCode = 1
              editDesignResult(this.form)
                      .then((res) => {
                        this.loading = false
                        if (res.code == 200) {
                          this.$message.success('提交成功')
                          //提交时，返回id
                          this.businessId = res.data || this.id;
                          this.setProcessConfig = this.processConfig;
                        }
                      })
                      .catch((res) => {
                        this.loading = false
                      })
            } else {
              this.loading = true
              this.form.statusCode = 1
              addDesignResult(this.form)
                      .then((res) => {
                        this.loading = false
                        if (res.code == 200) {
                          this.$message.success('提交成功')
                          //提交时，返回id
                          this.businessId = res.data || this.id;
                          this.setProcessConfig = this.processConfig;
                        }
                      })
                      .catch((res) => {
                        this.loading = false
                      })
            }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    editorContent(val) {
      this.form.resultInfo = JSON.parse(JSON.stringify(val))
      this.$refs.form1.validateField('resultInfo')
    },
    getDesignDetails() {
      let that = this
      getDesignDetails({ id: that.id }).then((res) => {
        that.form = { ...res.data }
        that.$nextTick(() => {
          that.form.projectId = res.data.projectId
        })

        that.dataAssement = res.data.fileList
        that.form.creator = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
      })
    },

    changeData() {
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    },

    handleOk() {
      if (this.selectRow.name.length > 30) {
        return this.$message.error('设计单位名称不能超过30个字符！')
      }
      this.visible = false
      this.form.designUnit = this.selectRow.name
      this.form.designUnitId = this.selectRow.id
      this.$refs.form1.validateField('designUnit')
    },

    onChangeTime(val) {
      this.form.drawTime = val.format('YYYY-MM-DD')
    }
  }
}
</script>
